/*
 * $LastChangedDate: 2007-06-21 19:48:55 +0200 (Thu, 21 Jun 2007) $
 * $LastChangedRevision: 206 $
 * $LastChangedBy: david $
 */


#include <iostream>
#include "Log.h"
#include "Server.h"
#include "ServerSocket.h"
#include "SocketException.h"
#include "FileMngr.h"

Server::Server() : PORT(4242), Thread()
{
	Log::println(*this, "Server creado");
}

/* Obtiene el FileLock para un fichero. */
FileLock* Server::getFileLock(std::string path)
{
	FileLock* lock;
	std::map<std::string, FileLock*>::iterator pos;

	pos = locks.find(path);
	if (pos != locks.end()) {
		lock = pos->second;
	} else {
		lock = new FileLock();
		locks[path] = lock;
	}
	return lock;
}

Server::~Server()
{
	/* nop */
}

void Server::run()
{
	try {
		ServerSocket server(PORT);
		Log::println(*this, "Server escuchando en el puerto ");
		while (true) {
			ServerSocket *new_sock = new ServerSocket();
			server.accept(*new_sock);
			Log::println(*this, "Aceptado conexión ", Log::CONNECTION);
			std::string path;
			*new_sock >> path;
			if (path == "KILL") {
				Log::println(*this, "Apagando servidor ...");
				*new_sock << "SERVIDOR APAGADO";
				break;
			}
			FileMngr *fm = new FileMngr(path, getFileLock(path), *new_sock);
			fm->start();
			*new_sock << "Creado FileMngr para " + path;
		}
	}
	catch (SocketException& e) {
		Log::println(*this, "Exception: " + e.description());
		exit(1);
	}
}
